<template>
  <view class="container">
    <view class="header">
      <text class="title">编辑收货地址</text>
      <text class="save-btn" @click="saveAddress">保存</text>
    </view>
    <view class="form-item">
      <label>姓名</label>
      <input v-model="formData.name" placeholder="请输入姓名" />
    </view>
    <view class="form-item">
      <label>电话</label>
      <input v-model="formData.phone" placeholder="请输入电话" />
    </view>
    <view class="form-item">
      <label>城市</label>
      <picker :range="cityOptions" range-key="name" @change="onCityChange">
        <input placeholder="请选择城市" :value="formData.city"  />
      </picker>
    </view>
    <view class="form-item">
      <label>详细地址</label>
      <input v-model="formData.department" placeholder="请输入详细地址" />
    </view>
    <view class="form-item">
      <label>门牌号</label>
      <input v-model="formData.houseNumber" placeholder="请输入门牌号" />
    </view>
  </view>
</template>

<script>
<<<<<<< HEAD
	import config from '../../config';
=======
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
export default {
  data() {
    return {
      formData: {
        _id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: ''
      },
      cityOptions: [
        { name: '杭州市' },
        { name: '北京市' },
        { name: '上海市' },
        { name: '广州市' },
        { name: '深圳市' },
        { name: '成都市' }
      ]
    };
  },
  onLoad(options) {
    if (options.id) {
      this.fetchAddressDetail(options.id);
    }
  },
  methods: {
    async fetchAddressDetail(addressId) {
      uni.showLoading({ title: '加载中...' });
      try {
        const response = await uni.request({
<<<<<<< HEAD
          url: config.URL+`/address?id=${addressId}`,
=======
          url: `https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address?id=${addressId}`,
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
          method: 'GET'
        });

        if (response.statusCode === 200) {
          const foundItem = response.data[0];
          if (foundItem) {
            this.formData = {
              _id: foundItem._id || foundItem.id,
              name: foundItem.name,
              phone: foundItem.phone,
              city: foundItem.city,
              department: foundItem.department,
              houseNumber: foundItem.houseNumber
            };
          } else {
            uni.showToast({ title: '未找到地址信息', icon: 'none' });
          }
        } else {
          uni.showToast({ 
            title: `获取地址失败: ${response.statusCode || '无响应'}`,
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取地址错误:', error);
        uni.showToast({ 
          title: '获取地址失败: ' + (error.message || '未知错误'),
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async saveAddress() {
      // 表单验证
      if (!this.formData.name || !this.formData.phone || !this.formData.city || 
          !this.formData.department || !this.formData.houseNumber) {
          uni.showToast({ title: '请填写完整信息', icon: 'none' });
          return;
      }

      uni.showLoading({ title: '保存中...' });
      try {
        // 先获取原数据
        const getRes = await uni.request({
<<<<<<< HEAD
          url: config.URL+`/address?id=${this.formData._id}`,
=======
          url: `https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address?id=${this.formData._id}`,
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
          method: 'GET'
        });

        if (getRes.statusCode === 200) {
          const originalData = getRes.data[0];
          if (originalData) {
            // 合并新数据
            const updatedData = {
              ...originalData,
              ...this.formData
            };

            // 发起更新请求
            const updateRes = await uni.request({
<<<<<<< HEAD
              url: config.URL+`/address/${originalData.id}`,
=======
              url: `https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/address/${originalData.id}`,
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
              method: 'PUT',
              data: updatedData,
              header: {
                'Content-Type': 'application/json'
              }
            });

            if (updateRes.statusCode === 200) {
              uni.showToast({ title: '保存成功', icon: 'success' });
              setTimeout(() => uni.navigateTo({
                url:"/pages/address/index"
<<<<<<< HEAD
              }), 2000);
=======
              }), 1500);
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
            } else {
              throw new Error(updateRes.data.message || '保存失败');
            }
          } else {
            throw new Error('未找到要更新的地址信息');
          }
        } else {
          throw new Error(`获取原数据失败: ${getRes.statusCode || '无响应'}`);
        }
      } catch (error) {
        console.error('保存错误:', error);
        uni.showToast({ 
          title: error.message || '保存失败', 
          icon: 'none' 
        });
      } finally {
        uni.hideLoading();
      }
    },
    onCityChange(e) {
      this.formData.city = this.cityOptions[e.detail.value].name;
    }
  }
};
</script>

<style scoped>
/* 全局样式 */
body {
  font-family: 'Open Sans', sans-serif;
  margin: 0;
  padding: 0;
  background-color: #eaf2f8;
}

.container {
  padding: 30px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  max-width: 600px;
  margin-bottom: 30px;
  animation: fadeInDown 0.5s ease;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.title {
  font-size: 24px;
  font-weight: 600;
  color: #444;
}

.save-btn {
  color: #00a2ff;
  text-decoration: none;
  font-size: 16px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.save-btn:hover {
  color: #0087e6;
}

.form-item {
  width: 100%;
  max-width: 600px;
  margin-bottom: 25px;
  animation: fadeInUp 0.5s ease;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-item label {
  display: block;
  margin-bottom: 10px;
  color: #444;
  font-size: 18px;
  font-weight: 500;
}

.form-item input {
  width: 80%;
  height: 50px;
  padding: 0 15px;
  border: 1px solid #d3e1ec;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  color: #333;
}

.form-item input::placeholder {
  color: #999;
}

.form-item input:focus {
  border-color: #00a2ff;
  outline: none;
  box-shadow: 0 0 8px rgba(0, 162, 255, 0.2);
}

/* 下拉选择器样式 */
.form-item picker {
  width: 80%;
  display: block;
}
.form-item picker input {
  width: 100%;
  cursor: pointer;
}
</style>
